package com.example.myweb.Service.Auth.Impl;

import com.example.myweb.Domain.Entity.*;
import com.example.myweb.Dto.*;
import com.example.myweb.Exception.CustomException;
import com.example.myweb.Repository.JpaRepository.ArticleRepository;
import com.example.myweb.Repository.JpaRepository.AttachmentRepository;
import com.example.myweb.Repository.JpaRepository.CategoryRepository;
import com.example.myweb.Repository.JpaRepository.ContentTopicRepository;
import com.example.myweb.Service.Auth.ArticleService;
import com.example.myweb.Service.Auth.PollService;
import com.example.myweb.Service.Auth.TopicService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private TopicService topicService;
    @Autowired
    private ContentTopicRepository contentTopicRepository;
    @Autowired
    private AttachmentRepository attachmentRepository;
    @Autowired
    private PollService pollService;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public Article createArticle(CreateArticleDTO request, User currentUser) {
        Category category = categoryRepository.findById(request.getCategoryId())
                .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));

        Article newArticle = new Article();
        newArticle.setTitle(request.getTitle());
        newArticle.setContent(request.getContent());
        newArticle.setCoverImageUrl(request.getCoverImageUrl());
        newArticle.setAuthor(currentUser);
        newArticle.setCategory(category);
        newArticle.setStatus(Article.ArticleStatus.PUBLISHED); // 默认直接发布

        Article savedArticle = articleRepository.save(newArticle);

        // 处理话题
        if (request.getTopics() != null && !request.getTopics().isEmpty()) {
            Set<Topic> topics = topicService.findOrCreateTopics(request.getTopics());
            List<ContentTopic> contentTopics = topics.stream().map(topic -> {
                ContentTopic contentTopic = new ContentTopic();
                contentTopic.setContentType(ContentTopic.ContentType.ARTICLE);
                contentTopic.setContentId(savedArticle.getArticleId());
                contentTopic.setTopic(topic);
                contentTopic.setArticle(savedArticle);
                return contentTopic;
            }).collect(Collectors.toList());
            contentTopicRepository.saveAll(contentTopics);
            topicService.incrementTopicHotScore(topics, 5); // 发布文章+5热度
        }

        // 处理投票附件
        if (request.getPoll() != null) {
            Attachment pollAttachment = new Attachment();
            pollAttachment.setContentType("ARTICLE");
            pollAttachment.setContentId(savedArticle.getArticleId());
            pollAttachment.setType(Attachment.AttachmentType.POLL);
            try {
                Map<String, Object> metadata = Map.of(
                        "question", request.getPoll().getQuestion(),
                        "options", request.getPoll().getOptions()
                );
                pollAttachment.setMetadata(objectMapper.writeValueAsString(metadata));
            } catch (JsonProcessingException e) {
                throw new CustomException("创建投票失败：无法序列化投票数据", HttpStatus.INTERNAL_SERVER_ERROR);
            }
            attachmentRepository.save(pollAttachment);
        }

        return savedArticle;
    }

    @Override
    @Transactional
    public ArticleDetailDTO getArticleById(Long articleId, User currentUser) {
        Article article = articleRepository.findById(articleId)
                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));

        // 异步更新浏览量（如果需要）
        // article.setViewCount(article.getViewCount() + 1);
        // articleRepository.save(article);

        return convertToDetailDto(article, currentUser);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<ArticleDetailDTO> getAllArticles(Pageable pageable, User currentUser) {
        Page<Article> articlePage = articleRepository.findAll(pageable);
        return articlePage.map(article -> convertToSummaryDto(article, currentUser));
    }

    @Override
    @Transactional
    public ArticleDetailDTO updateArticle(Long articleId, UpdateArticleDTO request, User currentUser) {
        Article articleToUpdate = articleRepository.findById(articleId)
                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));

        if (!articleToUpdate.getAuthor().getUserId().equals(currentUser.getUserId())) {
            throw new CustomException("无权修改他人文章", HttpStatus.FORBIDDEN);
        }

        articleToUpdate.setTitle(request.getTitle());
        articleToUpdate.setContent(request.getContent());
        articleToUpdate.setCoverImageUrl(request.getCoverImageUrl());

        if (!articleToUpdate.getCategory().getCategoryId().equals(request.getCategoryId())) {
            Category newCategory = categoryRepository.findById(request.getCategoryId())
                    .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));
            articleToUpdate.setCategory(newCategory);
        }

        // 话题更新逻辑 (简化为先清空再新增)
        // 1. 清空旧的话题关联
        contentTopicRepository.deleteByContentTypeAndContentId(ContentTopic.ContentType.ARTICLE, articleId);
        // 2. 添加新的话题关联
        if (request.getTopics() != null && !request.getTopics().isEmpty()) {
            Set<Topic> topics = topicService.findOrCreateTopics(request.getTopics());
            List<ContentTopic> contentTopics = topics.stream().map(topic -> {
                ContentTopic contentTopic = new ContentTopic();
                contentTopic.setContentType(ContentTopic.ContentType.ARTICLE);
                contentTopic.setContentId(articleId);
                contentTopic.setTopic(topic);
                return contentTopic;
            }).collect(Collectors.toList());
            contentTopicRepository.saveAll(contentTopics);
        }

        Article updatedArticle = articleRepository.save(articleToUpdate);
        return convertToDetailDto(updatedArticle, currentUser);
    }

    @Override
    @Transactional
    public void deleteArticle(Long articleId, User currentUser) {
        Article articleToDelete = articleRepository.findById(articleId)
                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));

        if (!articleToDelete.getAuthor().getUserId().equals(currentUser.getUserId())) {
            throw new CustomException("无权删除他人文章", HttpStatus.FORBIDDEN);
        }

        articleRepository.delete(articleToDelete);
    }

    // --- 后台管理方法 ---

    @Override
    @Transactional(readOnly = true)
    public Page<AdminArticleDetailDTO> getAllArticlesForAdmin(Pageable pageable) {
        Page<Article> articlePage = articleRepository.findAll(pageable);
        return articlePage.map(this::convertToAdminDto);
    }

    @Override
    @Transactional
    public void updateArticleStatusByAdmin(Long articleId, String statusStr) {
        Article article = articleRepository.findById(articleId)
                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
        try {
            Article.ArticleStatus status = Article.ArticleStatus.valueOf(statusStr.toUpperCase());
            article.setStatus(status);
            articleRepository.save(article);
        } catch (IllegalArgumentException e) {
            throw new CustomException("无效的文章状态: " + statusStr, HttpStatus.BAD_REQUEST);
        }
    }

    @Override
    @Transactional
    public void deleteArticleByAdmin(Long articleId) {
        if (!articleRepository.existsById(articleId)) {
            return;
        }
        articleRepository.deleteById(articleId);
    }

    // --- 辅助转换方法 ---

    private ArticleDetailDTO convertToDetailDto(Article article, User currentUser) {
        ArticleDetailDTO dto = new ArticleDetailDTO();
        dto.setArticleId(article.getArticleId());
        dto.setTitle(article.getTitle());
        dto.setContent(article.getContent());
        dto.setAuthor(new AuthorInfoDTO(article.getAuthor().getUserId(), article.getAuthor().getNickname(), article.getAuthor().getAvatarUrl()));
        dto.setCategory(new CategoryDTO(article.getCategory().getCategoryId(), article.getCategory().getName()));
        dto.setCoverImageUrl(article.getCoverImageUrl());
        dto.setViewCount(article.getViewCount());
        dto.setLikeCount(article.getLikeCount());
        dto.setCommentCount(article.getCommentCount());
        dto.setPublishTime(article.getPublishTime());
        dto.setLastUpdateTime(article.getLastUpdateTime());

        // 组装话题
        if (article.getContentTopics() != null) {
            dto.setTopics(article.getContentTopics().stream()
                    .map(ct -> ct.getTopic().getName())
                    .collect(Collectors.toList()));
        }

        // 组装投票结果
        attachmentRepository
                .findByContentTypeAndContentId("ARTICLE", article.getArticleId()).stream()
                .filter(att -> att.getType() == Attachment.AttachmentType.POLL)
                .findFirst()
                .ifPresent(pollAttachment -> {
                    PollResultDTO pollResult = pollService.getPollResults(pollAttachment.getAttachmentId(), currentUser);
                    dto.setPoll(pollResult);
                });

        return dto;
    }

    // 列表页使用的摘要DTO转换
    private ArticleDetailDTO convertToSummaryDto(Article article, User currentUser) {
        ArticleDetailDTO dto = convertToDetailDto(article, currentUser);
        // 列表页不返回完整内容，只返回摘要
        String content = article.getContent();
        if (content != null) {
            dto.setSummary(content.substring(0, Math.min(content.length(), 150)) + "...");
        }
        dto.setContent(null); // 清空完整内容
        return dto;
    }

    // 后台管理使用的DTO转换
    private AdminArticleDetailDTO convertToAdminDto(Article article) {
        AdminArticleDetailDTO dto = new AdminArticleDetailDTO();
        dto.setArticleId(article.getArticleId());
        dto.setTitle(article.getTitle());
        dto.setAuthorNickname(article.getAuthor().getNickname());
        dto.setAuthorId(article.getAuthor().getUserId());
        dto.setCategoryName(article.getCategory().getName());
        dto.setStatus(article.getStatus().name().toLowerCase());
        dto.setPublishTime(article.getPublishTime());
        dto.setViewCount(article.getViewCount());
        dto.setLikeCount(article.getLikeCount());
        dto.setCommentCount(article.getCommentCount());
        return dto;
    }
}

//@Service
//public class ArticleServiceImpl implements ArticleService {
//
//    @Autowired
//    private ArticleRepository articleRepository;
//    @Autowired
//    private CategoryRepository categoryRepository;
//
//    @Autowired
//    private TopicService topicService;
//    @Autowired
//    private ContentTopicRepository contentTopicRepository;
//
//    @Autowired
//    private AttachmentRepository attachmentRepository;
//
//    @Autowired
//    private PollService pollService;
//
//
//    @Override
//    @Transactional
//    public Article createArticle(CreateArticleDTO request, User currentUser) {
////        Category category = categoryRepository.findById(request.getCategoryId())
////                .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));
////
////        Article newArticle = new Article();
////        newArticle.setTitle(request.getTitle());
////        newArticle.setContent(request.getContent());
////        newArticle.setCoverImageUrl(request.getCoverImageUrl());
////        newArticle.setAuthor(currentUser);
////        newArticle.setCategory(category);
////
////        return articleRepository.save(newArticle);
//        Category category = categoryRepository.findById(request.getCategoryId())
//                .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));
//
//        Article newArticle = new Article();
//        // ... 设置 title, content, author, category 等...
//
//        Article savedArticle = articleRepository.save(newArticle);
//
//        // === 新增处理话题的逻辑 ===
//        if (request.getTopics() != null && !request.getTopics().isEmpty()) {
//            // 1. 查找或创建话题
//            Set<Topic> topics = topicService.findOrCreateTopics(request.getTopics());
//
//            // 2. 创建关联记录
//            List<ContentTopic> contentTopics = topics.stream().map(topic -> {
//                ContentTopic contentTopic = new ContentTopic();
//                contentTopic.setContentType(ContentTopic.ContentType.ARTICLE);
//                contentTopic.setContentId(savedArticle.getArticleId());
//                contentTopic.setTopic(topic);
//                return contentTopic;
//            }).collect(Collectors.toList());
//
//            // 3. 批量保存关联关系
//            contentTopicRepository.saveAll(contentTopics);
//        }
//        if (request.getTopics() != null && !request.getTopics().isEmpty()) {
//            Set<Topic> topics = topicService.findOrCreateTopics(request.getTopics());
//
//            // ... 保存关联关系 ...
//
//            // === 新增：为话题增加热度 ===
//            // 发布一篇新文章，可以认为热度+5
//            topicService.incrementTopicHotScore(topics, 5);
//        }
//        if (request.getPoll() != null) {
//            Attachment pollAttachment = new Attachment();
//            pollAttachment.setContentType("ARTICLE");
//            pollAttachment.setContentId(savedArticle.getArticleId());
//            pollAttachment.setType(Attachment.AttachmentType.POLL);
//
//            // 将投票的问题和选项序列化为JSON字符串
//            try {
//                Map<String, Object> metadata = Map.of(
//                        "question", request.getPoll().getQuestion(),
//                        "options", request.getPoll().getOptions()
//                );
//                pollAttachment.setMetadata(objectMapper.writeValueAsString(metadata));
//            } catch (JsonProcessingException e) {
//                throw new CustomException("创建投票失败：无法序列化投票数据", HttpStatus.INTERNAL_SERVER_ERROR);
//            }
//            attachmentRepository.save(pollAttachment);
//        }
//
//        return savedArticle;
//    }
//
//@Service
//public class ArticleServiceImpl implements ArticleService {
//
//    @Autowired
//    private ArticleRepository articleRepository;
//    @Autowired
//    private CategoryRepository categoryRepository;
//    @Autowired
//    private TopicService topicService;
//    @Autowired
//    private ContentTopicRepository contentTopicRepository;
//    @Autowired
//    private AttachmentRepository attachmentRepository;
//    @Autowired
//    private PollService pollService;
//
//    // ================== 注入 ObjectMapper ==================
//    @Autowired
//    private ObjectMapper objectMapper;
//    // =======================================================
//
//    @Override
//    @Transactional
//    public Article createArticle(CreateArticleDTO request, User currentUser) {
//        Category category = categoryRepository.findById(request.getCategoryId())
//                .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));
//
//        Article newArticle = new Article();
//        newArticle.setTitle(request.getTitle());
//        newArticle.setContent(request.getContent());
//        newArticle.setCoverImageUrl(request.getCoverImageUrl());
//        newArticle.setAuthor(currentUser);
//        newArticle.setCategory(category);
//        newArticle.setStatus(Article.ArticleStatus.PUBLISHED); // 默认直接发布
//
//        Article savedArticle = articleRepository.save(newArticle);
//
//        // 处理话题
//        if (request.getTopics() != null && !request.getTopics().isEmpty()) {
//            Set<Topic> topics = topicService.findOrCreateTopics(request.getTopics());
//            List<ContentTopic> contentTopics = topics.stream().map(topic -> {
//                ContentTopic contentTopic = new ContentTopic();
//                contentTopic.setContentType(ContentTopic.ContentType.ARTICLE);
//                contentTopic.setContentId(savedArticle.getArticleId());
//                contentTopic.setTopic(topic);
//                contentTopic.setArticle(savedArticle);
//                return contentTopic;
//            }).collect(Collectors.toList());
//            contentTopicRepository.saveAll(contentTopics);
//        }
//
//        // 处理投票附件
//        if (request.getPoll() != null) {
//            Attachment pollAttachment = new Attachment();
//            pollAttachment.setContentType("ARTICLE");
//            pollAttachment.setContentId(savedArticle.getArticleId());
//            pollAttachment.setType(Attachment.AttachmentType.POLL);
//            try {
//                Map<String, Object> metadata = Map.of(
//                        "question", request.getPoll().getQuestion(),
//                        "options", request.getPoll().getOptions()
//                );
//                // 使用注入的 objectMapper
//                pollAttachment.setMetadata(objectMapper.writeValueAsString(metadata));
//            } catch (JsonProcessingException e) {
//                throw new CustomException("创建投票失败：无法序列化投票数据", HttpStatus.INTERNAL_SERVER_ERROR);
//            }
//            attachmentRepository.save(pollAttachment);
//        }
//
//        return savedArticle;
//    }
////    @Override
////    @Transactional(readOnly = true)
////    public Page<ArticleDetailDTO> getAllArticles(Pageable pageable) {
////        Page<Article> articlePage = articleRepository.findAll(pageable);
////        // 对于列表，不包含完整内容，只包含摘要
////        return articlePage.map(article -> convertToDto(article, false));
////    }
//
//    @Override
//    @Transactional(readOnly = true)
//    public Page<ArticleDetailDTO> getAllArticles(Pageable pageable) {
//        Page<Article> articlePage = articleRepository.findAll(pageable);
//        // 对于列表，不包含完整内容，只包含摘要
//        return articlePage.map(article -> convertToDto(article, false));
//    }
//    @Override
//    @Transactional(readOnly = true)
//    public ArticleDetailDTO getArticleById(Long articleId, User currentUser) {
//        Article article = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//        article.setViewCount(article.getViewCount() + 1);
//         articleRepository.save(article);
//        return convertToDetailDto(article, currentUser);
//    }
//
//
//    // --- 后台管理方法 ---
//    @Override
//    @Transactional(readOnly = true)
//    public Page<AdminArticleDetailDTO> getAllArticlesForAdmin(Pageable pageable) {
//        Page<Article> articlePage = articleRepository.findAll(pageable);
//        return articlePage.map(this::convertToAdminDto);
//    }
//
//    @Override
//    @Transactional
//    public ArticleDetailDTO updateArticle(Long articleId, ArticleUpdateDTO request, User currentUser) {
//        // 1. 查找文章
//        Article articleToUpdate = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        // 2. 权限校验：确保当前登录用户是文章的作者
//        if (!articleToUpdate.getAuthor().getUserId().equals(currentUser.getUserId())) {
//            throw new CustomException("无权修改他人文章", HttpStatus.FORBIDDEN);
//        }
//
//        // 3. 更新文章属性
//        articleToUpdate.setTitle(request.getTitle());
//        articleToUpdate.setContent(request.getContent());
//        articleToUpdate.setCoverImageUrl(request.getCoverImageUrl());
//
//        // 4. 更新分类（如果分类有变动）
//        if (!articleToUpdate.getCategory().getCategoryId().equals(request.getCategoryId())) {
//            Category newCategory = categoryRepository.findById(request.getCategoryId())
//                    .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));
//            articleToUpdate.setCategory(newCategory);
//        }
//
//        // lastUpdateTime 会由 @UpdateTimestamp (如果你用了的话) 或 JPA 自动更新
//        Article updatedArticle = articleRepository.save(articleToUpdate);
//
//        // 5. 返回更新后的文章详情
//        return convertToDto(updatedArticle, true);
//    }
//    @Override
//    @Transactional
//    public void deleteArticle(Long articleId, User currentUser) {
//        Article articleToDelete = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        if (!articleToDelete.getAuthor().getUserId().equals(currentUser.getUserId())) {
//            throw new CustomException("无权删除他人文章", HttpStatus.FORBIDDEN);
//        }
//
//        articleRepository.delete(articleToDelete);
//    }
//    @Override
//    @Transactional
//    public void updateArticleStatusByAdmin(Long articleId, String status) {
//        Article article = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        // 这里可以对 status 字符串进行校验，确保它是合法的状态值
////         article.setStatus(Article.Status.valueOf(status.toUpperCase()));
//        // 假设你的 Article 实体有 status 字段
//
//        articleRepository.save(article);
//    }
//
//    // === 新增：这是给管理员删除任何文章用的 ===
//    @Override
//    @Transactional
//    public void deleteArticleByAdmin(Long articleId) {
//        // 管理员操作，不需要检查文章作者，只需要检查文章是否存在
//        if (!articleRepository.existsById(articleId)) {
//            // 如果文章不存在，可以直接返回，因为删除的目标已经不存在了
//            return;
//        }
//
//        // 直接删除
//        articleRepository.deleteById(articleId);
//    }
//
//    private AdminArticleDetailDTO convertToAdminDto(Article article) {
//        AdminArticleDetailDTO dto = new AdminArticleDetailDTO();
//        dto.setArticleId(article.getArticleId());
//        dto.setTitle(article.getTitle());
//        dto.setAuthorNickname(article.getAuthor().getNickname());
//        dto.setAuthorId(article.getAuthor().getUserId());
//        dto.setCategoryName(article.getCategory().getName());
//        // dto.setStatus(article.getStatus().name());
//        dto.setPublishTime(article.getPublishTime());
//        dto.setViewCount(article.getViewCount());
//        dto.setLikeCount(article.getLikeCount());
//        dto.setCommentCount(article.getCommentCount());
//        return dto;
//    }
//
//    private ArticleDetailDTO convertToDto(Article article, boolean includeContent) {
//        ArticleDetailDTO dto = new ArticleDetailDTO();
////        dto.setArticleId(article.getArticleId());
////        dto.setTitle(article.getTitle());
////
////        if (includeContent) {
////            dto.setContent(article.getContent());
////        } else {
////            // 生成摘要：取内容的前100个字符
////            String content = article.getContent();
////            dto.setSummary(content.substring(0, Math.min(content.length(), 100)) + "...");
////        }
////
////        dto.setCoverImageUrl(article.getCoverImageUrl());
////        dto.setViewCount(article.getViewCount());
////        dto.setLikeCount(article.getLikeCount());
////        dto.setCommentCount(article.getCommentCount());
////        dto.setPublishTime(article.getPublishTime());
////        dto.setLastUpdateTime(article.getLastUpdateTime());
////
////        dto.setAuthor(new AuthorInfoDTO(
////                article.getAuthor().getUserId(),
////                article.getAuthor().getNickname(),
////                article.getAuthor().getAvatarUrl()
////        ));
////
////        dto.setCategory(new CategoryDTO(
////                article.getCategory().getCategoryId(),
////                article.getCategory().getName()
////        ));
////
////        return dto;
//        if (article.getContentTopics() != null) {
//            List<String> topicNames = article.getContentTopics().stream()
//                    .map(contentTopic -> contentTopic.getTopic().getName())
//                    .collect(Collectors.toList());
//            dto.setTopics(topicNames);
//        }
//
//        return dto;
//    }
//    // --- 辅助转换方法 ---
//    private ArticleDetailDTO convertToDetailDto(Article article, User currentUser) {
//        ArticleDetailDTO dto = new ArticleDetailDTO();
//        // ... 设置 id, title, content, author, category, counts, time ...
//
//        // 查找并组装话题
//        // ...
//
//        // 查找并组装投票结果
//        Optional<Attachment> pollAttachmentOpt = attachmentRepository
//                .findByContentTypeAndContentId("ARTICLE", article.getArticleId()).stream()
//                .filter(att -> att.getType() == Attachment.AttachmentType.IMAGE) // 修正：应该是POLL
//                .filter(att -> att.getType() == Attachment.AttachmentType.POLL)
//                .findFirst();
//
//        pollAttachmentOpt.ifPresent(pollAttachment -> {
//            PollResultDTO pollResult = pollService.getPollResults(pollAttachment.getAttachmentId(), currentUser);
//            dto.setPoll(pollResult);
//        });
//
//        return dto;
//    }
//}
//



//    @Override
//    @Transactional(readOnly = true) // 查询操作使用只读事务，可以优化性能
//    public ArticleDetailDTO getArticleById(Long articleId, User currentUser) {
//        Article article = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        // 可以在这里增加浏览量+1的逻辑
//         article.setViewCount(article.getViewCount() + 1);
//         articleRepository.save(article);
//
//        return convertToDto(article, currentUser); // 包含完整内容
//    }

//    @Override
//    @Transactional(readOnly = true)
//    public Page<ArticleDetailDTO> getAllArticles(Pageable pageable) {
//        Page<Article> articlePage = articleRepository.findAll(pageable);
//        // 对于列表，不包含完整内容，只包含摘要
//        return articlePage.map(article -> convertToDto(article, false));
//    }

    // 辅助方法，用于转换 Entity -> DTO
//    private ArticleDetailDTO convertToDto(Article article, boolean includeContent) {
//        ArticleDetailDTO dto = new ArticleDetailDTO();
////        dto.setArticleId(article.getArticleId());
////        dto.setTitle(article.getTitle());
////
////        if (includeContent) {
////            dto.setContent(article.getContent());
////        } else {
////            // 生成摘要：取内容的前100个字符
////            String content = article.getContent();
////            dto.setSummary(content.substring(0, Math.min(content.length(), 100)) + "...");
////        }
////
////        dto.setCoverImageUrl(article.getCoverImageUrl());
////        dto.setViewCount(article.getViewCount());
////        dto.setLikeCount(article.getLikeCount());
////        dto.setCommentCount(article.getCommentCount());
////        dto.setPublishTime(article.getPublishTime());
////        dto.setLastUpdateTime(article.getLastUpdateTime());
////
////        dto.setAuthor(new AuthorInfoDTO(
////                article.getAuthor().getUserId(),
////                article.getAuthor().getNickname(),
////                article.getAuthor().getAvatarUrl()
////        ));
////
////        dto.setCategory(new CategoryDTO(
////                article.getCategory().getCategoryId(),
////                article.getCategory().getName()
////        ));
////
////        return dto;
//        if (article.getContentTopics() != null) {
//            List<String> topicNames = article.getContentTopics().stream()
//                    .map(contentTopic -> contentTopic.getTopic().getName())
//                    .collect(Collectors.toList());
//            dto.setTopics(topicNames);
//        }
//
//        return dto;
//    }

//    @Override
//    @Transactional
//    public ArticleDetailDTO updateArticle(Long articleId, ArticleUpdateDTO request, User currentUser) {
//        // 1. 查找文章
//        Article articleToUpdate = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        // 2. 权限校验：确保当前登录用户是文章的作者
//        if (!articleToUpdate.getAuthor().getUserId().equals(currentUser.getUserId())) {
//            throw new CustomException("无权修改他人文章", HttpStatus.FORBIDDEN);
//        }
//
//        // 3. 更新文章属性
//        articleToUpdate.setTitle(request.getTitle());
//        articleToUpdate.setContent(request.getContent());
//        articleToUpdate.setCoverImageUrl(request.getCoverImageUrl());
//
//        // 4. 更新分类（如果分类有变动）
//        if (!articleToUpdate.getCategory().getCategoryId().equals(request.getCategoryId())) {
//            Category newCategory = categoryRepository.findById(request.getCategoryId())
//                    .orElseThrow(() -> new CustomException("指定的分类不存在", HttpStatus.BAD_REQUEST));
//            articleToUpdate.setCategory(newCategory);
//        }
//
//        // lastUpdateTime 会由 @UpdateTimestamp (如果你用了的话) 或 JPA 自动更新
//        Article updatedArticle = articleRepository.save(articleToUpdate);
//
//        // 5. 返回更新后的文章详情
//        return convertToDto(updatedArticle, true);
//    }


    // === 实现新增的 deleteArticle 方法 ===
//    @Override
//    @Transactional
//    public void deleteArticle(Long articleId, User currentUser) {
//        // 1. 查找文章
//        Article articleToDelete = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        // 2. 权限校验
//        if (!articleToDelete.getAuthor().getUserId().equals(currentUser.getUserId())) {
//            // 在实际应用中，你可能还想允许管理员删除
//            // if (!articleToDelete.getAuthor().getUserId().equals(currentUser.getUserId()) && !currentUser.getRole().equals("ADMIN"))
//            throw new CustomException("无权删除他人文章", HttpStatus.FORBIDDEN);
//        }
//
//        // 3. 执行删除
//        // 注意：与这篇文章关联的点赞、收藏、评论等也需要被一并删除。
//        // 最好的方式是在数据库层面设置外键的级联删除 (ON DELETE CASCADE)。
//        // 如果没有设置，你需要在这里手动调用其他Repository来删除关联数据。
//        articleRepository.delete(articleToDelete);
//    }
    // 这是给普通用户删除自己的文章用的
//    @Override
//    @Transactional
//    public void deleteArticle(Long articleId, User currentUser) {
//        Article articleToDelete = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        if (!articleToDelete.getAuthor().getUserId().equals(currentUser.getUserId())) {
//            throw new CustomException("无权删除他人文章", HttpStatus.FORBIDDEN);
//        }
//
//        articleRepository.delete(articleToDelete);
//    }

//    // === 新增：这是给管理员删除任何文章用的 ===
//    @Override
//    @Transactional
//    public void deleteArticleByAdmin(Long articleId) {
//        // 管理员操作，不需要检查文章作者，只需要检查文章是否存在
//        if (!articleRepository.existsById(articleId)) {
//            // 如果文章不存在，可以直接返回，因为删除的目标已经不存在了
//            return;
//        }
//
//        // 直接删除
//        articleRepository.deleteById(articleId);
//    }

//    @Override
//    @Transactional(readOnly = true)
//    public Page<AdminArticleDetailDTO> getAllArticlesForAdmin(Pageable pageable) {
//        Page<Article> articlePage = articleRepository.findAll(pageable);
//        return articlePage.map(this::convertToAdminDto);
//    }

//    @Override
//    @Transactional
//    public void updateArticleStatusByAdmin(Long articleId, String status) {
//        Article article = articleRepository.findById(articleId)
//                .orElseThrow(() -> new CustomException("文章不存在", HttpStatus.NOT_FOUND));
//
//        // 这里可以对 status 字符串进行校验，确保它是合法的状态值
////         article.setStatus(Article.Status.valueOf(status.toUpperCase()));
//        // 假设你的 Article 实体有 status 字段
//
//        articleRepository.save(article);
//    }

    // 辅助方法
//    private AdminArticleDetailDTO convertToAdminDto(Article article) {
//        AdminArticleDetailDTO dto = new AdminArticleDetailDTO();
//        dto.setArticleId(article.getArticleId());
//        dto.setTitle(article.getTitle());
//        dto.setAuthorNickname(article.getAuthor().getNickname());
//        dto.setAuthorId(article.getAuthor().getUserId());
//        dto.setCategoryName(article.getCategory().getName());
//        // dto.setStatus(article.getStatus().name());
//        dto.setPublishTime(article.getPublishTime());
//        dto.setViewCount(article.getViewCount());
//        dto.setLikeCount(article.getLikeCount());
//        dto.setCommentCount(article.getCommentCount());
//        return dto;
//    }
//}